﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Service
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ExtMemberService
    {
        private readonly ExtMemberRepository _extMember;
        private readonly ICacheManager _cacheManager;
        private readonly string cacheKey;
        public ExtMemberService(ExtMemberRepository extMemberRepository, ICacheManager cacheManager)
        {
            _extMember = extMemberRepository;
            _cacheManager = cacheManager;
            cacheKey = _cacheManager.CacheName() + "ExtMember_main";
        }

        public async Task<Page<ExtMember>> GetPageListAsync(string keyword, int page, int limit, int? status)
        {
            return await _extMember.GetPageListAsync(keyword, page, limit, status);
        }

        /// <summary>
        /// 供前台使用，列出全部列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ExtMember>> GetAllAsync()
        {
            List<ExtMember> list = _cacheManager.Get<List<ExtMember>>(cacheKey);
            if (list == null)
            {
                list = await _extMember.GetAllListAsync("Id desc");
                _cacheManager.Set(cacheKey, list, TimeSpan.FromDays(10));
            }
            return list;
        }

        public virtual async Task<object> InsertAsync(ExtMember extMember)
        {
            _cacheManager.RemoveCacheAsync(cacheKey);
            return await _extMember.InsertAsync(extMember);
        }

        public async Task<ExtMember> GetEditAsync(int? id)
        {
            return await _extMember.GetAsync(id);
        }

        public async Task<int> UpdateAsync(ExtMember extMember, int id, int dyEdit)
        {
            ExtMember member = await _extMember.GetAsync(id);
            if (dyEdit == 1)
            {
                member.Sort = extMember.Sort;
                _cacheManager.RemoveCacheAsync(cacheKey);
                return await _extMember.UpdateAsync(member, id);
            }
            member.Id = id;
            member.Name = extMember.Name;
            member.Duties = extMember.Duties;
            member.Photo = extMember.Photo;
            member.Duty = extMember.Duty;
            member.Sort = extMember.Sort;
            member.Status = extMember.Status;
            _cacheManager.RemoveCacheAsync(cacheKey);
            return await _extMember.UpdateAsync(member, id);
        }


        public async Task<int> DeleteByPriKeyAsync(int id)
        {
            return await _extMember.DeleteByPriKeyAsync(id);
        }


    }
}
